<script setup>
import {
  deleteInternshipMaterialApi,
  fuzzyQueryApi,
  getInternshipMaterialListApi,
  studentFindEmploymentMaterialApi,
  studentFindInternshipMaterialApi,
  uploadInternshipMaterialInfoApi,
  uploadStudentEmploymentMaterialsApi,
  uploadStudentInternshipMaterialsApi
} from '@/api/job'
import Form from '@/components/User/Form.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/practice/table.vue'
import { showStatusMessage } from '@/utils/common/showMessage'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import FormJob from '@/components/Job/form.vue'
import axios from 'axios'
import { ElMessageBox, ElLoading } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
// **********************筛选表**********************
const formData = ref({
  desc: ''
})
const formModel = [
  {
    prop: 'desc',
    label: '材料',
    type: 'input'
  }
]
let btnOpt = [
  {
    name: '查询',
    btnType: '',
    prop: 'query'
  },
  {
    name: '重置',
    btnType: 'info',
    prop: 'reset'
  },
  {
    name: '添加',
    btnType: 'success',
    prop: 'add'
  }
]
function btnOptS() {
  if (userStore.userInfo.identity == '学生' || userStore.userInfo.identity == '辅导员') {
    btnOpt = [
      {
        name: '查询',
        btnType: '',
        prop: 'query'
      },
      {
        name: '重置',
        btnType: 'info',
        prop: 'reset'
      }
    ]
  } else {
    btnOpt = [
      {
        name: '查询',
        btnType: '',
        prop: 'query'
      },
      {
        name: '重置',
        btnType: 'info',
        prop: 'reset'
      },
      {
        name: '添加',
        btnType: 'success',
        prop: 'add'
      }
    ]
  }
}
btnOptS()
/**
 * 点击重置按钮
 */
function reset() {
  getTableData()
  pagizationRef.value.reset()
  selectFormRef.value.reset()
}

const formRef = ref(null)
const pagizationToatl = ref(null)

// 添加加载状态
const loading = ref(false)

/**
 * 获取表格数据
 */
async function getTableData(data) {
  loading.value = true
  try {
    const res = await studentFindEmploymentMaterialApi({
      ...data,
      account: userStore.userInfo.account,
      class: userStore.userInfo.class
    })
    tableData.value = res.data.map((item) => ({
      ...item,
      statusLabel: getStatusLabel(item.status)
    }))
    pagizationToatl.value = res.total
  } catch (error) {
    console.error('获取数据失败:', error)
    showStatusMessage({ status: 0, message: '获取数据失败' })
  } finally {
    loading.value = false
  }
}

// 添加状态标签映射
function getStatusLabel(status) {
  const statusMap = {
    0: { type: 'info', label: '待审核' },
    1: { type: 'success', label: '已通过' },
    2: { type: 'danger', label: '未通过' }
  }
  return statusMap[status] || { type: 'info', label: '未知状态' }
}

getTableData()
const pagizationRef = ref(null)
const selectFormRef = ref(null)

/**
 * 表单按钮点击事件
 * @param type 操作类型
 * @param data 表单数据
 */
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'add':
      addForm()
      break
    case 'output':
      exportToExcel()
      break
    case 'reset':
      reset(data)
      break
    case 'import':
      handleUpload(data)
      break
    case 'submit':
      handleSubmit(data)
      break
    default:
      break
  }
}

/**
 * 表单查询事件
 * @param {Object} data 查询条件
 */
const queryData = ref(null)
async function query(data) {
  console.log(data)

  queryData.value = data
  const res = await fuzzyQueryApi(data)
  tableData.value = res.data?.map((item) => {
    return {
      ...item
    }
  })
  pagizationToatl.value = res.total
  showStatusMessage(res)
  tableData.value = res.data
  pagizationToatl.value = res.total
}

// 列表数据
const tableData = ref([])
const columns = [
  {
    prop: 'desc',
    label: '实习材料名称'
  },
  {
    prop: 'material',
    label: '模版',
    display: 'button'
  },
  {
    prop: 'status',
    label: '状态',
    display: 'tag'
  },
  {
    prop: 'feedbackDesc',
    label: '结果反馈',
    display: 'feedback'
  }
]
const options = [
  {
    label: '上传材料',
    type: 'success',
    prop: 'submitMaterial'
  }
]
const docPreview = ref('')
const dialogViewVisible = ref(false)
// 下载材料
async function handletTableMaterial(data) {
  try {
    const loading = ElLoading.service({
      text: '文件下载中...'
    })

    const fileExt = data.material.split('.').pop()
    const res = await axios({
      method: 'get',
      url: data.material,
      responseType: 'blob'
    })

    const blob = new Blob([res.data], {
      type: 'application/octet-stream'
    })
    const fileName = `${data.desc}.${fileExt}`
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    loading.close()
  } catch (error) {
    console.error('下载失败:', error)
    showStatusMessage({ status: 0, message: '文件下载失败' })
  }
}
function handleDialogViewClose() {
  docPreview.value = ''
}
function handletTableSubmitMaterial(data) {
  console.log(data)
  dialogTableVisible.value = true
  FormJobData.value.studentMaterialDesc = data.desc
}
function handletTableFeedbackDesc(data) {
  ElMessageBox.alert(`${data.feedbackDesc}`, '查看反馈', {
    confirmButtonText: '确认'
  })
}
/**
 * 表格的操作事件
 * @param {Object} data  操作行的数据
 * @param {String} type 操作类型-'edit'-'delete'
 */
function handleTable(data, type) {
  // console.log(data, type)
  switch (type) {
    case 'material':
      handletTableMaterial(data)
      break
    case 'submitMaterial':
      handletTableSubmitMaterial(data)
      break
    case 'feedbackDesc':
      handletTableFeedbackDesc(data)
      break
    default:
      break
  }
}
// 分页器条数发生变化
function handleSizeChange(val) {
  const data = selectFormRef.value.getValue()
  console.log('条数发生变化')
  getTableData({ size: val, ...data })
  pagizationRef.value.reset()
}
// 分页器页数发生变化
function handleCurrentChange(page, size) {
  const data = selectFormRef.value.getValue()
  console.log('页数发生变化')
  getTableData({ page, size, ...data })
}

// 弹窗显示
const dialogTableVisible = ref(false)
const FormJobData = ref({
  studentMaterialDesc: '',
  studentMaterial: ''
})
const formJobOpt = [
  {
    prop: 'studentMaterialDesc',
    label: '实现材料名称',
    type: 'input',
    disabled: true
  },
  {
    prop: 'studentMaterial',
    label: '上传材料',
    type: 'studentMaterial'
  }
]
const btnJobOpt = [
  {
    name: '取消',
    btnType: 'info',
    prop: 'cancel'
  },
  {
    name: '提交',
    btnType: 'primary',
    prop: 'submit'
  }
]

const formJobRef = ref(null)
//dialog关闭前的回调
function handleDialogClose() {
  formJobRef.value.reset()
}
async function addForm() {
  dialogTableVisible.value = true
}

async function handleSubmit(data) {
  console.log(data)
  let info = {
    studentAccount: userStore.userInfo.account,
    studentClass: userStore.userInfo.class,
    studentMaterial: data.studentMaterial,
    studentMaterialDesc: data.studentMaterialDesc,
    studentName: userStore.userInfo.name,
    studentMajor: userStore.userInfo.major,
    studentCollege: userStore.userInfo.college
  }

  const res = await uploadStudentEmploymentMaterialsApi(info)
  showStatusMessage(res)
  dialogTableVisible.value = false
  getTableData()
  handleDialogClose()
}
</script>

<template>
  <div class="employment-material">
    <div class="page-header">
      <h2>就业材料提交</h2>
    </div>

    <!-- 搜索表单 -->
    <Form
      :data="formData"
      :formOpt="formModel"
      :btnOpt="btnOpt"
      @handleForm="handleForm"
      ref="selectFormRef"
      class="search-form"
    />

    <!-- 表格 -->
    <Table :tableData="tableData" :columns="columns" :options="options" @handleTable="handleTable">
      <template #firstColumn>
        <el-table-column type="index" label="序号" width="80" align="center" />
      </template>

      <template #status="{ row }">
        <el-tag :type="row.statusLabel.type">
          {{ row.statusLabel.label }}
        </el-tag>
      </template>
    </Table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <Pagization
        ref="pagizationRef"
        :total="pagizationToatl"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>

    <!-- 上传材料对话框 -->
    <el-dialog
      v-model="dialogTableVisible"
      :title="FormJobData.studentMaterialDesc ? '上传就业材料' : '新增就业材料'"
      width="600px"
      @close="handleDialogClose"
      destroy-on-close
    >
      <FormJob
        ref="formJobRef"
        :data="FormJobData"
        :form-opt="formJobOpt"
        :btn-opt="btnJobOpt"
        @handleForm="handleForm"
      />
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="dialogViewVisible"
      title="文件预览"
      top="5vh"
      width="80%"
      @close="handleDialogViewClose"
    >
      <div class="preview-container">
        <embed :src="docPreview" type="application/pdf" width="100%" height="800px" />
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.employment-material {
  padding: 20px;
  display: flex;
  flex-direction: column;
  .page-header {
    margin-bottom: 20px;

    h2 {
      font-size: 24px;
      color: #303133;
      margin: 0;
    }
  }

  .page-content {
    .search-form {
      margin-bottom: 20px;
    }

    .table-card {
      margin-bottom: 20px;
    }

    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .preview-container {
    background: #f5f7fa;
    border-radius: 4px;
    padding: 10px;
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .employment-material {
    padding: 10px;

    .page-content {
      .el-card {
        margin: 10px 0;
      }
    }
  }
}
</style>
